/* eslint-disable no-shadow */
/* eslint-disable no-unused-vars */
import React, { memo, useState, useEffect, useCallback } from "react";
import Taro, {
  useRouter,
  usePageScroll,
  useReachBottom,
} from "@tarojs/taro";
import { useSelector, useDispatch, shallowEqual } from "react-redux";
import { updateState } from "@/store/actions/global";
import { View } from "@tarojs/components";
import { Loading, Empty, Tabs, Tab } from "@antmjs/vantui";
import debounce from "lodash/debounce";
import axios from "@/axios";
import { getRecipeHeat } from "@/axios/api/recipe";
import Authorization from "@/components/Authorization";
import RecipeItem from "@/components/RecipeItem";
import BackTop from "@/components/BackTop";
import Navbar from "@/components/Navbar";
import toast from "@/utils/toast";
import { themeColor } from "../../utils/config";
import "./index.less";

const Index = () => {
  const router = useRouter();
  const dispatch = useDispatch();
  const { globalData } = useSelector(
    (state) => ({ globalData: state.globalData }),
    shallowEqual
  );
  const { isLogin, showBackTop, systemInfo, navbarHeight } = globalData;
  const { screenHeight } = systemInfo
  const [active, setActive] = useState(0);
  const [isLoading, setLoading] = useState(false);
  const [rankListData, setRankListData] = useState([]);
  const [isMore, setIsMore] = useState(false);
  const [pageNum, setPageNum] = useState(1);


  const onChange = ({ detail: { index } }) => {
    setRankListData([]);
    getRank(index + 1, 1);
    setActive(index);
  };
  const handleClick = useCallback(
    debounce(
      (type, id,username) => {
        console.log("CLICK", type, id);
        let url = "";
        if (type === "recipe") {
          url = "/pages/recipeInfo/index?recipe_id=" + id;
        }
        if (type === "user") {
          url = `/pages/userCenter/index?user_id=${id}&username=${username}`;
        }
        if (!isLogin) {
          dispatch(
            updateState({
              isShowGrant: true,
            })
          );
        } else {
          jumpTo(url);
        }
      },
      500,
      {
        leading: true,
        trailing: false,
      }
    ),
    [isLogin]
  );
  const jumpTo = (url) => {
    Taro.navigateTo({
      url,
    });
  };
  const getRank = (type = 1, page = 1) => {
    setLoading(true);
    axios.get(getRecipeHeat, { params: { type, page } }).then((res) => {
      const { data, code } = res;
      if (code === 200) {
        // const { list, pageNum, pageSize, total } = data;
        console.log(data, res.msg);
        const { pageNum, isMore, list } = data;
        if (page === 1) {
          setRankListData(list);
          setIsMore(isMore)
          setPageNum(pageNum)
        } else {
          setRankListData((pre) => [...pre, ...list]);
          setIsMore(isMore)
          setPageNum(pageNum)
        }
      }
      setLoading(false);
    });
  };
  const getListDom = (type = 1) => {
    return rankListData.map((item, index) => {
      return (
        <RecipeItem
          key={item.recipe_id}
          data={item}
          num={index + 1}
          handleClick={handleClick}
        ></RecipeItem>
      );
    });
  };
  useEffect(() => {
    if (!isLogin) {
      dispatch(
        updateState({
          isShowGrant: true,
        })
      );
      return;
    }
    getRank();
  }, [isLogin, dispatch]);
  usePageScroll((res) => {
    const flag = res.scrollTop > screenHeight * 1.5;
    if (flag !== showBackTop) {
      dispatch(
        updateState({
          showBackTop: flag,
        })
      );
    }
  });
  useReachBottom(() => {
    if (isMore) {
      getRank(active + 1, pageNum + 1);
    }
  });
  return (
    <View className='rank'>
      <Navbar title='热门菜谱' arrow='true'></Navbar>
      <View className='tab' style={{ top: navbarHeight }}>
        <Tabs active={active} onChange={onChange}>
          <Tab title='今日'>
          </Tab>
          <Tab title='本周'>
          </Tab>
          <Tab title='本月'>
          </Tab>
        </Tabs>
      </View>
      <View className='block'></View>
      <View className='rank-list'>
        {!rankListData.length && !isLoading ? <Empty description='暂无菜谱' /> : (getListDom())}
      </View>
      {isLoading ? (
        <View className='loading'>
          <Loading color={themeColor} size='28px' />
        </View>
      ) : null}
      <Authorization canClose={false}></Authorization>
      <View>{showBackTop ? <BackTop top={.75 * screenHeight} /> : null}</View>
    </View>
  );
};

export default memo(Index);
